package service

import (
	"context"
	pb "doctor-srv/basic/proto"
	"doctor-srv/basic/config"
	"doctor-srv/handler/model"
	"time"
)

type StatisticsService struct {
	pb.UnimplementedStatisticsServer
}

// GetConsultationStats 获取问诊量统计
func (s *StatisticsService) GetConsultationStats(ctx context.Context, req *pb.GetConsultationStatsReq) (*pb.GetConsultationStatsResp, error) {
	var consultations []model.Consultation
	query := config.DB.Model(&model.Consultation{})

	if req.DoctorId > 0 {
		query = query.Where("doctor_id = ?", req.DoctorId)
	}
	if req.StartDate != "" {
		query = query.Where("created_at >= ?", req.StartDate)
	}
	if req.EndDate != "" {
		query = query.Where("created_at <= ?", req.EndDate)
	}

	var totalCount int64
	query.Count(&totalCount)

	// 按日期统计
	var dailyStats []*pb.DailyStats
	rows, err := query.
		Select("DATE(created_at) as date, COUNT(*) as count").
		Group("DATE(created_at)").
		Rows()
	
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var date string
		var count int64
		rows.Scan(&date, &count)
		dailyStats = append(dailyStats, &pb.DailyStats{
			Date:  date,
			Count: count,
		})
	}

	return &pb.GetConsultationStatsResp{
		TotalCount: totalCount,
		DailyStats: dailyStats,
	}, nil
}

// GetDoctorPerformance 获取医生业绩统计
func (s *StatisticsService) GetDoctorPerformance(ctx context.Context, req *pb.GetDoctorPerformanceReq) (*pb.GetDoctorPerformanceResp, error) {
	var consultationCount int64
	query := config.DB.Model(&model.Consultation{}).Where("doctor_id = ?", req.DoctorId)
	
	if req.StartDate != "" {
		query = query.Where("created_at >= ?", req.StartDate)
	}
	if req.EndDate != "" {
		query = query.Where("created_at <= ?", req.EndDate)
	}
	query.Count(&consultationCount)

	// 统计病历完成数
	var completedRecordCount int64
	recordQuery := config.DB.Model(&model.MedicalRecord{}).Where("doctor_id = ?", req.DoctorId)
	if req.StartDate != "" {
		recordQuery = recordQuery.Where("created_at >= ?", req.StartDate)
	}
	if req.EndDate != "" {
		recordQuery = recordQuery.Where("created_at <= ?", req.EndDate)
	}
	recordQuery.Count(&completedRecordCount)

	// 计算平均评分
	var averageRating float64
	config.DB.Model(&model.ConsultationRating{}).
		Joins("JOIN consultations ON consultation_ratings.consultation_id = consultations.id").
		Where("consultations.doctor_id = ?", req.DoctorId).
		Select("AVG(consultation_ratings.rating)").
		Scan(&averageRating)

	return &pb.GetDoctorPerformanceResp{
		ConsultationCount:     consultationCount,
		CompletedRecordCount:  completedRecordCount,
		AverageRating:         averageRating,
	}, nil
}

// GetMedicineSalesStats 获取药品销售统计
func (s *StatisticsService) GetMedicineSalesStats(ctx context.Context, req *pb.GetMedicineSalesStatsReq) (*pb.GetMedicineSalesStatsResp, error) {
	query := config.DB.Table("medicine_orders").
		Joins("JOIN prescriptions ON medicine_orders.prescription_id = prescriptions.id").
		Joins("JOIN prescription_items ON prescription_items.prescription_id = prescriptions.id")

	if req.StartDate != "" {
		query = query.Where("medicine_orders.created_at >= ?", req.StartDate)
	}
	if req.EndDate != "" {
		query = query.Where("medicine_orders.created_at <= ?", req.EndDate)
	}

	var totalSales int64
	query.Count(&totalSales)

	// 统计销量排名
	topN := req.TopN
	if topN <= 0 {
		topN = 10
	}

	var salesItems []*pb.MedicineSalesItem
	rows, err := query.
		Select("prescription_items.medicine_id, prescription_items.medicine_name, SUM(prescription_items.quantity) as sales_count, SUM(prescription_items.price * prescription_items.quantity) as sales_amount").
		Group("prescription_items.medicine_id").
		Order("sales_count DESC").
		Limit(int(topN)).
		Rows()

	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var medicineId int64
		var medicineName string
		var salesCount int64
		var salesAmount float64
		rows.Scan(&medicineId, &medicineName, &salesCount, &salesAmount)
		salesItems = append(salesItems, &pb.MedicineSalesItem{
			MedicineId:   medicineId,
			MedicineName: medicineName,
			SalesCount:   salesCount,
			SalesAmount:  salesAmount,
		})
	}

	return &pb.GetMedicineSalesStatsResp{
		TotalSales: totalSales,
		Items:      salesItems,
	}, nil
}

// GetPatientSatisfactionStats 获取患者满意度统计
func (s *StatisticsService) GetPatientSatisfactionStats(ctx context.Context, req *pb.GetPatientSatisfactionStatsReq) (*pb.GetPatientSatisfactionStatsResp, error) {
	query := config.DB.Model(&model.ConsultationRating{})

	if req.StartDate != "" {
		startTime, _ := time.Parse("2006-01-02", req.StartDate)
		query = query.Where("created_at >= ?", startTime)
	}
	if req.EndDate != "" {
		endTime, _ := time.Parse("2006-01-02", req.EndDate)
		query = query.Where("created_at <= ?", endTime)
	}

	var totalRatings int64
	query.Count(&totalRatings)

	var averageRating float64
	query.Select("AVG(rating)").Scan(&averageRating)

	// 评分分布
	var distribution []*pb.RatingDistribution
	rows, err := config.DB.Model(&model.ConsultationRating{}).
		Select("rating, COUNT(*) as count").
		Group("rating").
		Order("rating").
		Rows()

	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var rating int32
		var count int64
		rows.Scan(&rating, &count)
		distribution = append(distribution, &pb.RatingDistribution{
			Rating: rating,
			Count:  count,
		})
	}

	return &pb.GetPatientSatisfactionStatsResp{
		AverageRating: averageRating,
		TotalRatings:  totalRatings,
		Distribution:  distribution,
	}, nil
}

